
import os
import struct
from FieldFormat import FieldFormat
from Config import DataFileName
import json

class ConfigDataGen:

    # 保存文件
    @staticmethod
    def Save(inbytes, datapath):
        datapath += DataFileName

        filedir = os.path.dirname(datapath)
        if os.path.exists(filedir) == False:
            os.makedirs(filedir)

        savebytes = inbytes
        file = open(datapath, 'w',encoding="utf-8")
        file.write(savebytes)
        file.close()
    
    @staticmethod
    def Encode2Bytes(format, val):
        
        if format == "i":
            if val == None or val == "":
                val = -1
            bytes = int(val)
        elif format == "?":
            if val == None or val == "":
                val = 0
            bytes = bool(val)
        elif format == "s":
            bytes = val
        elif format == "i[]":
            if val == None or val == "":
                val = "[]"
            bytes = json.loads(val)
        elif format == "s[]":
            if val == None or val == "":
                val = "[]"
            bytes = json.loads(val)
        elif format == "j":
            if val == None or val == "":
                val = "[]"
            bytes = json.loads(val)
        return bytes

    # 文件生成函数
    @staticmethod
    def Process(table):
        #按行读取
        rows = table.nrows
        #保存关键字
        keys = []
        types = []
        #保存结果
        result = []
        for i in range(rows):
            if i == 0:
                keys = table.row_values(i)#保存关键字
            elif i == 1:
                types = table.row_values(i)
            elif i == 2:
                pass
            else:
                record = {}
                cnt = 0
                # 将Excel文件的数据存入字典中
                for item in table.row_values(i):
                    type = types[cnt]
                    type = type.lower()
                    format = FieldFormat.Type2format[type][0]
                    record[keys[cnt]] = ConfigDataGen.Encode2Bytes(format, item)
                    cnt += 1
                # 将字典存入列表
                result.append(record)
        
        return json.dumps(result, indent=4)

